package br.com.iswe.gwt.ui.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.Widget;

public abstract class BaseValidator implements Validator {

	public static final CommonConstants commonConstants = (CommonConstants) GWT.create(CommonConstants.class);
	public static final CommonMessages commonMessages = (CommonMessages) GWT.create(CommonMessages.class);

	
	protected List<ValidationHandler> validationHandlers = new ArrayList<ValidationHandler>();
	protected String name;
	protected String label;
	protected Object item;
	protected boolean enabled = true;
	
	public BaseValidator() {
		
	}
	
	public BaseValidator(String nome,String label, Object item) {
		this.name = nome;
		this.label = label;
		this.item = item;
		validationHandlers.add(new ValidationHandlerImpl());
	}
	
	public BaseValidator(String label) {
		this.label = label;
	}

	public void valid(Widget widget){
		for (int i = 0; i < validationHandlers.size(); i++) {
			ValidationHandler handler = (ValidationHandler)validationHandlers.get(i);
			handler.valid(widget);
		}
	}

	public void notValid(Widget widget, String msg){
		for (int i = 0; i < validationHandlers.size(); i++) {
			ValidationHandler handler = (ValidationHandler)validationHandlers.get(i);
			handler.notValid(widget, msg);
		}
	}
	
	public boolean isEmpty(String valor){
		if(valor == null){
			return true;
		}
		return valor.trim().length() == 0;
	}
	
	public final boolean validate() {
		boolean result = true;
		if(enabled){
			result = validateImpl();
		}
		return result;
	}
	
	protected abstract boolean validateImpl();

	public Object getItem() {
		return item;
	}

	public void setItem(Object item) {
		this.item = item;
	}

	public String getName() {
		return name;
	}

	public void setName(String nome) {
		this.name = nome;
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public void addValidationHandler(ValidationHandler validationHandler) {
		this.validationHandlers.add(validationHandler);
	}

	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	public List<ValidationHandler> getValidationHandlers() {
		return validationHandlers;
	}
	
}
